Intellij預設Spring Boot的Application設定檔是Application.properties,你也可以把它改成Application.yaml,當properties檔內容一多相較於yaml檔會比較不好閱讀,它的層級結構就不是那麼明顯,以下我們就來談談yaml文件檔如何撰寫。以下可以比較一下可讀性。
資料來源:https://www.baeldung.com/spring-boot-yaml-vs-properties
選取場景web與lombak
使用它可以簡化JavaBean的設定,在Class上方寫上註解@Data可以幫你自動生成constructer、getter/setter、toString、EqualsHashCode
YAML是"YAML Ain't a Markup Language"(YAML不是一種標記語言)的縮寫。YAML的意思其實是:"Yet Another Markup Language"(仍是一種標記語言),附檔名以yaml 或 yml結尾。
employee:
name: 'andy\n132'
entryDay: 2023/5/20 09:00:00
age: 35
isEmployee: true
supervisor:
name: "novak\n 456"
age: 42
birthDay: 2018/10/12
text[1]: bbb
text[0]: aaa
family-Members[1]:
name: tim
age: 2
family-Members[0]:
age: 3
name: tom
pets:
c2:
name: mimi
age: 2
c1:
age: 3
name: wang
employee.name=andy
employee.age=35
employee.entryDay=2023/5/20 09:00:00
employee.isEmployee=true
employee.supervisor.name=novak
employee.supervisor.age=42
employee.supervisor.birthDay=2018/10/12
employee.supervisor.text[0]=aaa
employee.supervisor.text[1]=bbb
employee.family-Members[0].name=tom
employee.family-Members[0].age=3
employee.family-Members[1].name=tim
employee.family-Members[1].age=2
employee.pets.c1.name=wang
employee.pets.c1.age=3
employee.pets.c2.name=mimi
employee.pets.c2.age=2
@Component
@ConfigurationProperties(prefix = "employee")
@Data
public class Employee {
private String name;
private Integer age;
private Date entryDay;
private Boolean isEmployee;
private Supervisor supervisor; //嵌套对象
private List<FamilyMember> familyMembers; //数组(里面是对象)
private Map<String,Pet> cats; //表示Map
}
@Data
public class FamilyMember {
private String name;
private Integer age;
}
@Data
public class Supervisor {
private String name;
private Integer age;
private Date birthDay;
private List<String> text; //数组
}
@Data
public class Pet {
private String name;
private Integer age;
}